/*
 * @Author: CoderLPF
 * @Date: 2020-03-18 12:32:15
 * @LastEditTime: 2020-04-20 19:46:41
 * @LastEditors: CoderLPF
 * @Description: 
 * @FilePath: \fzx-system-fd\src\api\axios.js
 */
// 创建axios实例并对拦截器进行配置
import axios from 'axios';
import qs from 'qs';



// 创建 axios 实例
let service = axios.create({
    headers: {
        
        // 'Access-Control-Allow-Origin': '*',
        // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
    },
    timeout: 60000
});

//service.defaults.baseURL = '/api';

// 设置 post、put 默认 Content-Type
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
service.defaults.headers.post['Content-Type'] = 'application/json';
service.defaults.headers.put['Content-Type'] = 'application/json';

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        if (config.method === 'post' || config.method === 'put') {
            // post、put 提交时，将对象转换为string, 为处理Java后台解析问题
            config.data = JSON.stringify(config.data);
        }
        var token = window.sessionStorage.getItem("token");
        if (token) config.headers.common["token"] = token;
            // 请求发送前进行处理

        //如何直接在url地址栏中，传数组参数
        config.paramsSerializer = function(params) {
            return qs.stringify(params, { arrayFormat: 'repeat' });
        };


        return config;
    },
    (error) => {
        // 请求错误处理
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        let { data } = response;
        return data;
    },
    (error) => {
        console.log("拦截错误");
        console.log(error);
        let info = {},
            { status, statusText, data } = error.response;
        if (!error.response) {
            info = {
                code: 5000,
                msg: 'Network Error'
            };
        } else {
            // 此处整理错误信息格式
            info = {
                code: status,
                data: data,
                msg: statusText
            };
        }
        console.log(info);
        return info;
    }
);

/**
 * 创建统一封装过的 axios 实例
 * @return {AxiosInstance}
 */
export default function() {
    return service;
}